package com.aioething.iot.hook;

import io.emqx.exhook.HookProviderGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class ExHookServer {
    private static final Logger logger = LogManager.getLogger(ExHookServer.class);

    @Value("${emqx.hook.port}")
    private Integer port;
    @Autowired
    private HookProviderGrpc.HookProviderImplBase hookProvider;

    private Server server;

    @PostConstruct
    public void start() throws InterruptedException {
        new Thread(() -> {
            try {
                init();
            } catch (IOException e) {
                logger.error(e);
            }
        }).start();
        blockUntilShutdown();
    }

    public void init() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(hookProvider)
                .build().start();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                ExHookServer.this.stop();
            } catch (InterruptedException e) {
                logger.error(e);
            }
        }));
    }
    private void stop() throws InterruptedException {
        if (server != null) {
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
